# -*- coding: utf-8 -*-
# @Time : 2021/9/4 9:29
# @Author : 唐宁
# @Site : 获取数据库连接池
# @File : DbConnector.py
# @Software: PyCharm
from config.MysqlDB import MysqlDb
from config.Page import Page
from config.Setting import settings
from exception.ErrorCodeEnum import ErrorCodeEnum
from exception.ErrorCodeException import ErrorCodeException


def getDb():
    return DbConnector()


class DbConnector:

    def __init__(self):
        self.db = MysqlDb(settings.DB_URL, settings.DB_PORT, settings.DB_ACCOUNT, settings.DB_PWD, settings.DB_NAME)

    def __enter__(self):
        return self.db

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.db.__del__()

    def select_list(self, sql, vo):
        """
        查询列表方法
        :param sql: sql 语句
        :param vo:  返回实体
        :return: 列表
        """
        return self.db.select_list(sql, vo)

    def select_one(self, sql, vo):
        """
        查询单数据方法
        :param sql: sql语句
        :param vo: 返回实体
        :return: 实体
        """
        return self.db.select_one(sql, vo)

    def select_page(self, sql, page_number, page_size, vo):
        """
        分页查询方法
        :param sql: sql
        :param page_number: 页码
        :param page_size: 大小
        :param vo: 实体
        :return: Page
        """
        total, rows = self.db.select_page(sql, page_number, page_size, vo)
        # 计算当前所在页
        pages = int(total / page_size)
        if pages == 0:
            pages = 1
        return Page(page_number, page_size, rows, total, pages)

    def excuse_one(self, sql):
        """
        执行更新或删除-单行
        :param sql: sql语句
        :return:
        """
        rowcount = self.db.execute_db(sql)
        if rowcount != 1:
            raise ErrorCodeException(ErrorCodeEnum.NO, "操作失败")

    def excuse_many(self, sql, size):
        """
        执行更新或删除-多行
        :param sql: sql语句
        :param size: 期望行数
        :return:
        """
        rowcount = self.db.execute_db(sql)
        if rowcount != size:
            raise ErrorCodeException(ErrorCodeEnum.NO, "操作失败")
